<template>
  <div class="cost-summary">
    <ProTable
      ref="order_data_breakdown_table"
      :immediate="false"
      :pagination="true"
      :search-form="formList"
      :columns="columns"
      :request="serviceDetailCountPage"
      :onRequestSuccess="requestSuccessCallback"
      :before-search-submit="beforeSearchSubmit"
    >
      <template #extra>
        <Authc permissions="trade:settlement:report:orderDataBreakdown:export">
          <Button type="primary" @click="exportExcel">下载</Button>
        </Authc>
      </template>
    </ProTable>

    <Modal
      v-model="exportModal"
      title="选择要下载的数据"
      @on-ok="submitExportExcel"
      @on-cancel="cancelExportExcel">
      <Row>
        <Col v-for="(item, index) in exportSection" :key="index" span="4">
          <span @click="selectExportSection(item)" v-bind:class="{ selectSectionItem: selectExportSectionItem &&item.id=== selectExportSectionItem.id}">{{item.start}} 至 {{item.end}}</span>
        </Col>
      </Row>
    </Modal>
  </div>
</template>

<script>
import { omit } from 'lodash'
import ProTable from '@/components/ProTable';
import { serviceDetailCountPage,serviceDetailCountExport,getOrderDictionary,getMerchantAllMerchant,getMerchantAllOrg } from '@/api/statement';
import {getDateYMD,getDateRangeDate} from '@/utils/date';
import util from '@/utils/util'
import Authc from "@/components/Authc";

export default {
  name: 'OrderDataBreakdown',
  components: {
    ProTable,
    Authc
  },
  data() {
    return {
      exportModal:false,
      exportSection:[],
      selectExportSectionItem:{},
      formList: [
        {
          type: 'range',
          name: 'date',
          label: '统计周期',
          value: '',
          props: {
            placeholder: '请选择',
            format: 'yyyy年MM月dd日'
          }
        },
        {
          type: 'date',
          name: 'year',
          label: '按年统计',
          value: '',
          props: {
            placeholder: '请选择',
            type: 'year',
            format: 'yyyy年'
          }
        },
        {
          type: 'select',
          name: 'orderSource',
          label: '场景',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: []
          }
        },
        {
          type: 'select',
          name: 'organizationCode',
          label: '组织机构',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [],
            clearable:true,
            filterable:true
          }
        },
        {
          type: 'select',
          name: 'merchantCode',
          label: '商户名称',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [],
            clearable:true,
            filterable:true
          }
        },
      ],
      columns: [
        {
          title: '统计周期',
          key: 'cycle_name',
          align: 'center',
        },
        {
          title: '订单状态',
          key: 'service_name',
          align: 'center',
        },
        {
          title: '场景',
          key: 'orderSourceName',
          align: 'center',
        },
        {
          title: '组织架构',
          key: 'organizationName',
          align: 'center',
        },
        {
          title: '商户名称',
          key: 'merchantName',
          align: 'center',
        },
        {
          title: '产品名称',
          key: 'productName',
          align: 'center',
        },
        {
          title: '销售金额',
          key: 'orderAmount',
          align: 'center',
        },
        {
          title: '优惠金额',
          key: 'discountAmount',
          align: 'center',
        },
        {
          title: '结算金额',
          key: 'cost_amount',
          align: 'center',
        },
        {
          title: '笔数',
          key: 'count',
          align: 'center',
        }
      ]
    };
  },
  created() {
    this.initSearchValue()
  },
  methods: {
    serviceDetailCountPage,
    beforeSearchSubmit(data) {
      return omit(this.searchDateHandler(data), 'date')
    },
    searchDateHandler(data){
      const { date,year,currentPage,pageSize } = data

      const [startDate, endDate] = getDateRangeDate(date)
      if(startDate){
        data.dayCycleStart = util.formatDate(startDate)
      }
      if(endDate){
        data.dayCycleEnd = util.formatDate(endDate)
      }
      if(currentPage){
        data.currentPage = currentPage
      }
      if(pageSize){
        data.pageSize = pageSize
      }
      data.year = getDateYMD(year)[0]

      return data
    },
    async initSearchValue(){
      const orderSourceList=await getOrderDictionary("orderSource")
      const selectRevenueTypeList = orderSourceList.map(({value, key}) => {
        return {
          value: key,
          label: value
        };
      });
      this.setSearchOptionListInitValue("orderSource",selectRevenueTypeList)

      // 查询商户
      const merchantList=await getMerchantAllMerchant();
      const selectMerchantList = merchantList.map(({merchantCode, merchantName}) => {
        return {
          value: merchantCode,
          label: merchantName
        };
      });
      this.setSearchOptionListInitValue("merchantCode",selectMerchantList)

      // 查询机构
      const orgList=await getMerchantAllOrg();
      const selectOrgList = orgList.map(({organizationCode, organizationName}) => {
        return {
          value: organizationCode,
          label: organizationName
        };
      });
      this.setSearchOptionListInitValue("organizationCode",selectOrgList)
    },
    setSearchOptionListInitValue(name,value){
      this.formList.map(item=>{
        if(item.name===name && item.props){
          item.props.optionList=value
        }
      })
    },
    async selectExportSection(item){
      this.selectExportSectionItem=item
    },
    //查询成功回调
    async requestSuccessCallback(res){
      if(res && res.data.pagination){
        const total=res.data.pagination.total||0
        if(total){
          const sections=Math.ceil(total/5000)
          let newExportSection=[]
          for (let i = 1; i <= sections; i++) {
            newExportSection.push({
              id:i,
              start:(i-1)*5000===0?1:(i-1)*5000,
              end:i*5000
            })
          }
          console.log(this.exportSection)
          this.exportSection=newExportSection
        }else{
          this.exportSection=[]
        }
      }else{
        this.exportSection=[]
      }
    },
    async exportExcel() {
      this.exportModal=true
    },
    async submitExportExcel(){
      if(!this.selectExportSectionItem || !this.selectExportSectionItem.id){
        this.$Message.warning("请选择要导出的数据区间");
        return
      }
      let data=this.$refs['order_data_breakdown_table'].getSearchParams()
      const newData=this.searchDateHandler(data);
      const res=await  serviceDetailCountExport({...newData,...this.selectExportSectionItem})
      util.exportExcle(res, '订单数据统计明细')
    },
    async cancelExportExcel(){
      this.exportModal=false
      this.selectExportSectionItem={}
    },
  }
};
</script>

<style>
.selectSectionItem{
  color: #2b85e4;
}
</style>
